package com.ysjy.course.controller;

import com.github.pagehelper.PageInfo;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.PromptMessage;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.dto.course.CourseClassDto;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.common.utils.StringUtil;
import com.ysjy.course.model.OrgCourse;
import com.ysjy.course.model.YsCoursePackage;
import com.ysjy.course.service.CourseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(description = "课程管理")
@RequestMapping("/course/manage")
@Slf4j
public class CourseManageController extends BaseController {

    @Autowired
    private CourseService courseService;

    @ApiOperation(value = "查询数量(课程、托管)")
    @RequestMapping(value = "getCourseCount", method = RequestMethod.GET)
    public ResultDTO<Map<String, Object>> getCourseCount(
            @ApiParam(value = "组织ID", defaultValue = "1", required = true) @RequestParam(name = "orgId", required = true) Long orgId) {
        UserDto userDto = getUserByLogin();
        if (userDto == null) {
            return new ResultDTO<>(ErrorCode.USER_NOT_EXIST);
        }
        try {
            HashMap<String, Object> params = new HashMap<>();
            if (null != orgId && 1 != orgId) {
                params.put("orgId",orgId);
            }
            return new ResultDTO<>(courseService.getCourseCount(params));
        } catch (Exception e) {
            log.error("***********ClassInfoManageController.page******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "运营平台课程列表(采集列表)")
    @RequestMapping(value = "getCourseListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<OrgCourse>> getCourseListByPage(
            @ApiParam(value = "名称（模糊搜索）", required = false) @RequestParam(name = "title", required = false) String title,
            @ApiParam(value = "副标题（模糊搜索）", required = false) @RequestParam(name = "subtitle", required = false) String subtitle,
            @ApiParam(value = "授课方式 1面授 2双师", required = false) @RequestParam(name = "type", required = false) Integer type,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            if (userDto.getOrgId() != 1) params.put("orgId",userDto.getOrgId());
            if (!StringUtil.isEmpty(title)) params.put("title", title);
            if (!StringUtil.isEmpty(subtitle)) params.put("subtitle", subtitle);
            PageInfo<OrgCourse> pageInfo = courseService.getListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取课程详情")
    @RequestMapping(value = "getCourse", method = RequestMethod.GET)
    public ResultDTO<PageInfo<OrgCourse>> getCourse(
            @ApiParam(value = "唯一标识", required = true) @RequestParam(name = "uniqueId", required = true) String uniqueId) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            OrgCourse orgCourse = courseService.getCourseByUniqueId(uniqueId);
            if (orgCourse != null) return ResultDTO.successResult(orgCourse);
            else return ResultDTO.errorResult(PromptMessage.LOAD_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "运营平台添加 or 编辑课程",notes = "{\"title\":\"课程名称\",\"subtitle\":\"副标题\",\"logo\":\"https://qiniu.childrenonline.cn/Fin5cd36X2FCZOPEaNhU0qZCpq-x\",\"tagId\":2,\"type\":1,\"timeNum\":3,\"courseTimeList\":[{\"title\":\"书法第1课\"},{\"title\":\"书法第2课\"},{\"title\":\"书法第3课\"}],\"introduce\":\"课程简介\",\"content\":\"教学大纲\",\"gradeIds\":\"47,48\",\"gradeNames\":\"八年级,九年级\",\"amount\":3,\"courseTimeAmount\":1,\"teachingMaterialAmount\":1,\"teachingMaterialIntroduce\":\"教材介绍\"}")
    @RequestMapping(value = "putCourse", method = RequestMethod.POST)
    public ResultDTO<Boolean> putCourse(
            @Valid @RequestBody OrgCourse data){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            data.setOrgId(userDto.getOrgId());
            return courseService.putCourse(data);
        } catch (Exception e) {
            e.printStackTrace();
//            return ResultDTO.errorResult(PromptMessage.INFO_IS_NULL);
            return ResultDTO.errorResult(e.getMessage());
        }
    }

    @ApiOperation(value = "删除课程")
    @RequestMapping(value = "delCourse", method = RequestMethod.POST)
    public ResultDTO<Boolean> delCourse(
        @ApiParam(value = "唯一标识", required = true) @RequestParam(name = "id", required = true) Long id){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            courseService.deleteByPrimaryKey(id);
            return new ResultDTO<>(true);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.errorResult(PromptMessage.INFO_IS_NULL);
        }
    }

    @ApiOperation(value = "删除机构课程")
    @RequestMapping(value = "delOrgCourse", method = RequestMethod.POST)
    public ResultDTO<Boolean> delOrgCourse(
        @ApiParam(value = "唯一标识", required = true) @RequestParam(name = "id", required = true) Long id){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return courseService.deleteOrgCourseByPrimaryKey(id);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDTO.errorResult(PromptMessage.INFO_IS_NULL);
        }
    }

    @ApiOperation(value = "获取机构课程详情")
    @RequestMapping(value = "getOrgCourse", method = RequestMethod.GET)
    public ResultDTO<OrgCourse> getOrgCourse(
            @ApiParam(value = "唯一标识", required = true) @RequestParam(name = "uniqueId", required = true) String uniqueId) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            OrgCourse orgCourse = courseService.getOrgCourseByUniqueId(uniqueId,null);
            if (orgCourse != null) return ResultDTO.successResult(orgCourse);
            else return ResultDTO.errorResult(PromptMessage.LOAD_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "机构课程列表")
    @RequestMapping(value = "getOrgCourseListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<OrgCourse>> getOrgCourseListByPage(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "名称（模糊搜索）", required = false) @RequestParam(name = "title", required = false) String title,
            @ApiParam(value = "副标题（模糊搜索）", required = false) @RequestParam(name = "subtitle", required = false) String subtitle,
            @ApiParam(value = "上架学校（模糊搜索）", required = false) @RequestParam(name = "orgName", required = false) String orgName,
            @ApiParam(value = "授课方式 1面授 2双师", required = false) @RequestParam(name = "type", required = false) Integer type,
            @ApiParam(value = "上架状态：0未上架 1上架", required = false) @RequestParam(name = "shelvesStatus", required = false) Integer shelvesStatus,
            @ApiParam(value = "学年", required = false) @RequestParam(name = "schoolYear", required = false) Integer schoolYear,
            @ApiParam(value = "学期", required = false) @RequestParam(name = "semester", required = false) String semester,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("orgId", orgId);
            if (!StringUtil.isEmpty(title)) params.put("title", title);
            if (!StringUtil.isEmpty(subtitle)) params.put("subtitle", subtitle);
            if (!StringUtil.isEmpty(orgName)) params.put("orgName", orgName);
            if (!StringUtil.isEmpty(semester)) params.put("semester", semester);
            params.put("shelvesStatus", shelvesStatus);
            params.put("schoolYear", schoolYear);
            PageInfo<OrgCourse> pageInfo = courseService.getOrgListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "机构课程列表(选择使用，例添加班级时)")
    @RequestMapping(value = "getOrgCourseList", method = RequestMethod.GET)
    public ResultDTO<List<OrgCourse>> getOrgCourseList(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "报名状态 0未开始、1报名中、2已结束", required = false) @RequestParam(name = "signUpStatus", required = false) Integer signUpStatus,
            @ApiParam(value = "上架状态：0未上架 1上架", required = false) @RequestParam(name = "shelvesStatus", required = false) Integer shelvesStatus) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("orgId", orgId);
            params.put("signUpStatus",signUpStatus);
            params.put("shelvesStatus",shelvesStatus);
            List<OrgCourse> pageInfo = courseService.getOrgCourseList(params);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "机构端添加 or 编辑课程",notes = "{\"title\":\"课程名称\",\"subtitle\":\"副标题\",\"logo\":\"https://qiniu.childrenonline.cn/Fin5cd36X2FCZOPEaNhU0qZCpq-x\",\"tagId\":2,\"siteId\":5,\"type\":1,\"timeNum\":3,\"courseTimeList\":[{\"title\":\"书法第1课\"},{\"title\":\"书法第2课\"},{\"title\":\"书法第3课\"}],\"introduce\":\"课程简介\",\"content\":\"教学大纲\",\"gradeIds\":\"47,48\",\"gradeNames\":\"八年级,九年级\",\"amount\":3,\"courseTimeAmount\":1,\"teachingMaterialAmount\":1,\"teachingMaterialIntroduce\":\"教材介绍\",\"courseUniqueId\":\"2022052011066588\",\"orgIds\":1452,\"orgNames\":\"紫城中学\",\"schoolYear\":2021,\"semester\":\"暑假班\",\"maxSignUpNum\":99,\"signUpEndTime\":1653463992769,\"signUpStartTime\":1653463992769,\"startTime\":1653463992769,\"endTime\":1653463992769,\"classTime\":\"星期三 09:00~10:00,星期五 09:00~10:00\",\"teacherId\":1}")
    @RequestMapping(value = "putOrgCourse", method = RequestMethod.POST)
    public ResultDTO<Boolean> putOrgCourse(
            @Valid @RequestBody OrgCourse data){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            return courseService.putOrgCourse(data);
        } catch (Exception e) {
            e.printStackTrace();
//            return ResultDTO.errorResult(PromptMessage.INFO_IS_NULL);
            return ResultDTO.errorResult(e.getMessage());
        }
    }

    @ApiOperation(value = "机构端批量上下架课程")
    @RequestMapping(value = "changeShelvesStatus", method = RequestMethod.POST)
    public ResultDTO changeShelvesStatus(
            @ApiParam(value = "id(多个,号隔开)", required = true) @RequestParam(name = "ids", required = true) String ids,
            @ApiParam(value = "上架状态：0未上架 1上架", required = true) @RequestParam(name = "shelvesStatus", required = true) Integer shelvesStatus
    ){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            courseService.changeShelvesStatus(ids,shelvesStatus);
            return ResultDTO.successResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO<>(false);
    }

    @ApiOperation(value = "学校添加 or 编辑课程包",notes = "{\"title\":\"暑期托管1\",\"logo\":\"https://qiniu.childrenonline.cn/Fin5cd36X2FCZOPEaNhU0qZCpq-x\",\"introduce\":\"简介简介\",\"content\":\"服务内容服务内容服务内容\",\"openPurchaseNotes\":true,\"purchaseNotes\":\"购买须知\",\"orgIds\":\"1452\",\"amount\":1,\"orgNames\":\"紫城中学\",\"courseUniqueIds\":\"2022072814060623,2022071515543922\",\"signUpEndTime\":1653463992769,\"signUpStartTime\":1653463992769,\"trusteeshipUniqueIds\":\"2022072810565160\"}")
    @RequestMapping(value = "putCoursePackage", method = RequestMethod.POST)
    public ResultDTO<Boolean> putCoursePackage(
            @Valid @RequestBody YsCoursePackage data){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            if (StringUtil.isEmpty(data.getCourseUniqueIds()) && StringUtil.isEmpty(data.getTrusteeshipUniqueIds())){
                return ResultDTO.errorResult("课程与托管列表不能都为空");
            }
            if (data.getOpenPurchaseNotes() == null) data.setOpenPurchaseNotes(false);
            return courseService.putCoursePackage(data);
        } catch (Exception e) {
            e.printStackTrace();
//            return ResultDTO.errorResult(PromptMessage.INFO_IS_NULL);
            return ResultDTO.errorResult(e.getMessage());
        }
    }

    @ApiOperation(value = "课程包分页列表")
    @RequestMapping(value = "getCoursePackageListByPage", method = RequestMethod.GET)
    public ResultDTO<PageInfo<YsCoursePackage>> getCoursePackageListByPage(
            @ApiParam(value = "机构ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
            @ApiParam(value = "名称（模糊搜索）", required = false) @RequestParam(name = "title", required = false) String title,
            @ApiParam(value = "上架状态：0未上架 1上架", required = false) @RequestParam(name = "shelvesStatus", required = false) Integer shelvesStatus,
            @ApiParam(value = "页码", required = true, defaultValue = "1") @RequestParam(name = "pageNo", required = true, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = true, defaultValue = "10") @RequestParam(name = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("orgId", orgId);
            if (!StringUtil.isEmpty(title)) params.put("title", title);
            params.put("shelvesStatus", shelvesStatus);
            PageInfo<YsCoursePackage> pageInfo = courseService.getCoursePackageListByPage(params, pageNo, pageSize);
            return ResultDTO.successResult(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "获取课程包详情")
    @RequestMapping(value = "getCoursePackage", method = RequestMethod.GET)
    public ResultDTO<YsCoursePackage> getCoursePackage(
            @ApiParam(value = "唯一标识", required = true) @RequestParam(name = "uniqueId", required = true) String uniqueId) {
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            YsCoursePackage data = courseService.getCoursePackageByUniqueId(uniqueId,null);
            if (data != null) return ResultDTO.successResult(data);
            else return ResultDTO.errorResult(PromptMessage.LOAD_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "课程包批量上下架课程")
    @RequestMapping(value = "packageChangeShelvesStatus", method = RequestMethod.POST)
    public ResultDTO packageChangeShelvesStatus(
            @ApiParam(value = "id(多个,号隔开)", required = true) @RequestParam(name = "ids", required = true) String ids,
            @ApiParam(value = "上架状态：0未上架 1上架", required = true) @RequestParam(name = "shelvesStatus", required = true) Integer shelvesStatus
    ){
        try {
            UserDto userDto = this.getUserByLogin();
            if (null == userDto) {
                return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
            }
            courseService.packageChangeShelvesStatus(ids,shelvesStatus);
            return ResultDTO.successResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDTO<>(false);
    }

}